package com.daichi.yygh.user.controller.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daichi.yygh.common.helper.JwtHelper;
import com.daichi.yygh.common.result.Result;
import com.daichi.yygh.model.user.UserInfo;
import com.daichi.yygh.user.service.UserInfoService;
import com.daichi.yygh.user.utils.HttpClientUtils;
import com.daichi.yygh.user.utils.WxUtils;
import com.daichi.yygh.user.vo.WeixinVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "微信操作接口")
@Controller
@RequestMapping("api/ucenter/wx")
public class WeixinApiController {

    private final UserInfoService userInfoService;

    @Autowired
    public WeixinApiController(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @ApiOperation(value = "扫码后回调方法")
    @GetMapping("callback")
    public String callback(String code, String state) {

        try {
            // 获取临时票据 code，拿着code请求微信获得access_token和openid
            WeixinVo weixinVo = getTokenAndOpenidByCode(code);

            // 查看数据库有无已经绑定openid的用户，如果没有就新建用户让他绑定手机
            UserInfo userInfo = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("openid", weixinVo.getOpenid()));
            if (userInfo == null) {
                // 通过access_token和openid获取用户信息
                userInfo = getUserInfoByWx(weixinVo);
                userInfoService.save(userInfo);
            }

            //返回name和token字符串
            Map<String, String> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            //判断userInfo是否有手机号，如果手机号为空，返回openid
            //如果手机号不为空，返回openid值是空字符串
            //前端判断：如果openid不为空，绑定手机号，如果openid为空，不需要绑定手机号
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //使用jwt生成token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

            return "redirect:" + WxUtils.YYGH_BASE_URL + "/weixin/callback"
                    + "?token=" + map.get("token")
                    + "&openid=" + map.get("openid")
                    + "&name=" + URLEncoder.encode(map.get("name"), "utf-8");

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private UserInfo getUserInfoByWx(WeixinVo weixinVo) throws Exception {

        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=%s" +
                "&openid=%s";
        String userInfoUrl = String.format(baseUserInfoUrl, weixinVo.getAccessToken(), weixinVo.getOpenid());

        // 访问查询接口
        String resultInfo = HttpClientUtils.get(userInfoUrl);
        WeixinVo wxResult = JSON.parseObject(resultInfo, WeixinVo.class);

        //封装用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setOpenid(wxResult.getOpenid());
        userInfo.setNickName(wxResult.getNickname());
        userInfo.setStatus(1);

        return userInfo;

    }

    private WeixinVo getTokenAndOpenidByCode(String code) throws Exception {

        StringBuilder baseAccessTokenUrl = new StringBuilder()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                WxUtils.WX_OPEN_APP_ID,
                WxUtils.WX_OPEN_APP_SECRET,
                code);

        // 使用httpclient请求 accessTokenUrl
        String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

        // 封装返回结果
        WeixinVo weixinVo = JSON.parseObject(accessTokenInfo, WeixinVo.class);
        return weixinVo;

    }


    @ApiOperation(value = "生成微信扫描二维码，返回生成二维码需要的参数")
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect() {

        Map<String, Object> map = new HashMap<>();

        try {
            map.put("appid", WxUtils.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            map.put("redirect_uri", URLEncoder.encode(WxUtils.WX_OPEN_REDIRECT_URL, "UTF-8"));
            map.put("state", System.currentTimeMillis() + "");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        return Result.ok(map);

    }
}
